using MSScriptControl;
using System;
using System.Runtime.InteropServices;
namespace Lyh.Train.Common.Convertor
{
	public class ScriptEngine
	{
		private ScriptControl msc;
		public event RunErrorHandler RunError;
		public event RunTimeoutHandler RunTimeout;
		public ScriptLanguage Language
		{
			get
			{
				return (ScriptLanguage)Enum.Parse(typeof(ScriptLanguage), this.msc.Language, false);
			}
			set
			{
				this.msc.Language = value.ToString();
			}
		}
		public int Timeout
		{
			get
			{
				return 0;
			}
		}
		public bool AllowUI
		{
			get
			{
				return this.msc.AllowUI;
			}
			set
			{
				this.msc.AllowUI = value;
			}
		}
		public bool UseSafeSubset
		{
			get
			{
				return this.msc.UseSafeSubset;
			}
			set
			{
				this.msc.UseSafeSubset = true;
			}
		}
		public ScriptEngine() : this(ScriptLanguage.VBscript)
		{
		}
		public ScriptEngine(ScriptLanguage language)
		{
            this.msc = new ScriptControlClass();
			this.msc.UseSafeSubset = true;
            this.msc.Language = language.ToString(); 
            ((DScriptControlSource_Event)this.msc).Error += new DScriptControlSource_ErrorEventHandler(ScriptEngine_Error);
            ((DScriptControlSource_Event)this.msc).Timeout += new DScriptControlSource_TimeoutEventHandler(ScriptEngine_Timeout);
		}
		public object Eval(string expression, string codeBody)
		{
			this.msc.AddCode(codeBody);
			return this.msc.Eval(expression);
		}
		public object Eval(ScriptLanguage language, string expression, string codeBody)
		{
			if (this.Language != language)
			{
				this.Language = language;
			}
			return this.Eval(expression, codeBody);
		}
		public object Run(string mainFunctionName, object[] parameters, string codeBody)
		{
			this.msc.AddCode(codeBody);
			object[] array = parameters;
			return this.msc.Run(mainFunctionName, ref array);
		}
		public object Run(ScriptLanguage language, string mainFunctionName, object[] parameters, string codeBody)
		{
			if (this.Language != language)
			{
				this.Language = language;
			}
			return this.Run(mainFunctionName, parameters, codeBody);
		}
		public void Reset()
		{
			this.msc.Reset();
		}
		private void OnError()
		{
			if (this.RunError != null)
			{
				this.RunError();
			}
		}
		private void OnTimeout()
		{
			if (this.RunTimeout != null)
			{
				this.RunTimeout();
			}
		}
		private void ScriptEngine_Error()
		{
			this.OnError();
		}
		private void ScriptEngine_Timeout()
		{
			this.OnTimeout();
		}
	}
}
